import redis
import requests
from lxml import etree
import json
import execjs

redis_conn = redis.Redis(host='localhost', port=6379, db=1, decode_responses=True)
# 加密密钥
secretKey = "qnbyzzwmdgghmcnm"

with open("decrypt.js", "r", encoding="utf-8") as f:
    js_code = execjs.compile(
        f.read()
    )

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}

# 配置参数
REDIS_LIST_KEY = "decode_article_list"
BATCH_SIZE = 1000  # 调整为每1000条批量插入一次
count_one = 0
count_two = 0

pipe = redis_conn.pipeline()

for page in range(1, 18022):
    url = f"http://ggzy.zwfwb.tj.gov.cn/jyxx/index_{page}.jhtml"
    response = requests.get(url, headers=headers, verify=False)

    html_str = response.content.decode()
    root = etree.HTML(html_str)
    print(f"第{page}页")
    data_list = root.xpath("//ul[@class='article-list2']/li")
    for data in data_list:
        count_one += 1
        title = "".join(data.xpath(".//a/text()")).strip()
        date = "".join(data.xpath(".//div[@class='list-times']/text()")).strip()
        link = "".join(data.xpath(".//a/@url"))
        decode_link = js_code.call("encryptUrl", link, secretKey)
        print(count_one, title)
        # 再根据加密后的连接，获取文件链接
        response_two = requests.get(decode_link, headers=headers, verify=False)
        html_string = response_two.content.decode()
        tree = etree.HTML(html_string)
        link_list = tree.xpath("//div[@class='content-article']/div[@id='content']//a")

        # 如果没有文件则跳过该页
        if link_list:
            for result in link_list:
                count_two += 1
                filename = "".join(result.xpath("./text()")).strip()
                filename_link = "".join(result.xpath("./@href")).strip().rstrip("*")
                print(f"数量:{count_two}", filename, filename_link)
                json_str = {
                    "title": title,
                    "filename": filename,
                    "filename_link": filename_link,
                }
                pipe.rpush(REDIS_LIST_KEY, json.dumps(json_str))

                if count_two % BATCH_SIZE == 0:
                    pipe.execute()
                    print(f"已批量插入 {BATCH_SIZE} 条数据（当前总数: {count_two}）")

if count_two % BATCH_SIZE != 0:
    try:
        pipe.execute()
        print(f"最后一批插入 {count_two % BATCH_SIZE} 条数据")
    except Exception as e:
        print(f"最后一批提交失败: {e}")

print(f"全部完成！共爬取 {count_two} 条数据")
